<template>
  <div>
    <el-drawer
      v-model="dialogVisible"
      :title="dialogStatus==='create'?'新增': (dialogStatus === 'view' ? '查看' : '编辑')"
      width="800px"
      @close="reset"
    >
      <div class="scene-dialog">
        <p>基本信息</p>
        <el-form 
          ref="articleFormRef"
          :model="formItem" 
          :rules="rules"
          label-width="100"
          label-position="top"
          :disabled="!isDisabled"
        >
          <el-form-item label="场景名称" prop="sceneName">
            <el-input v-model="formItem.sceneName" />
          </el-form-item>

          <el-form-item label="所属组织" prop="orgId">
            <org-tree-select ref="orgSelectRef" v-model="formItem.orgId" />
          </el-form-item>
        
          <el-form-item label="场景描述" prop="sceneDes">
            <el-input v-model="formItem.sceneDes" />
          </el-form-item>

          <el-form-item label="场景图片:" prop="scenePic" class="add-no">
            <el-upload 
              :file-list="formItem.uploadPhotoDtoList"
              accept=".jpg,.jpeg,.png,.gif" 
              list-type="picture-card"
              :show-file-list="true"
              :action="`/base-api/file/upload`" 
              :headers="headers" 
              :on-success="(data: any, uploadFile: any)=>handleUploadSuccess(data, uploadFile, 'PH', 'XC')"
              :on-error="handleUploadError"
              :on-remove="removeItem"
              :on-preview="handlePictureCardPreview"
              name="files"
              style="display: inline-block; margin: 0 10px 0 0; vertical-align: middle;"
              auto-upload
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  仅支持jpg、gif、png格式；大小为5M以内
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="选择设备" prop="equipIdList">
            <div>
              <div class="exist">
                <el-tag
                  v-for="tag in (formItem.equipList as equipItem[])"
                  :key="tag.id"
                  :closable="isDisabled"
                  type="info"
                  @close="onExistEquipDel(tag.id)"
                >
                  {{ tag.equipName }}
                </el-tag>
              </div>

              <el-cascader
                v-if="isDisabled"
                :options="availEquipList"
                :props="equipCasProps"
                :show-all-levels="false"
                @change="onEquipChange"
              />
            </div>
          </el-form-item>

        </el-form>

      </div>
        
      <template #footer v-if="isDisabled">
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="dialogStatus==='create'?createData():updateData()"
          >确 定</el-button>
        </span>
      </template>
    </el-drawer>
    <el-dialog v-model="dialogVisible2">
      <center><img w-full :src="dialogImageUrl" alt="Preview Image" /></center>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { addScene, apiGetOrgEquipList, editScene, equipItem, equipList, equipOrgItem, sceneEquipment } from '@/api/collect'
import { validate } from '@/utils/validate'
import { getToken } from '@/utils/user';
import OrgTreeSelect from '@/components/OrgTreeSelect/index.vue'

const isDisabled = ref(true)

const formItem = reactive({
  sceneName: '',
  orgId: null,
  sceneDes: '',
  scenePic: '',
  equipIdList: [],
  equipList: [],
  uploadPhotoDtoList: [],
})
  
const rules = reactive({
  sceneName: [{ required: true, message: '请输入', trigger: 'blur' }],
  orgId: [{ required: true, message: '请选择', trigger: 'change' }],
})

const dialogVisible = ref(false)
const dialogStatus = ref('create')

const reset = () => {
  formItem.uploadPhotoDtoList = []
  formItem.equipList = []
  formItem.equipIdList = []
  if (!articleFormRef) return
  articleFormRef.value.resetFields()
  isDisabled.value = false
}

const articleFormRef = ref(null)

const data = reactive({
  list: [] as any
})

const props = {
  label: 'equipName',
  children: 'children',
}

const getEquipment = () => {
  sceneEquipment(formItem.orgId)
  .then((res)=>{
    console.log('resEquip', res.data)
    data.list = res.data[0].equipList
  })
  .catch((err)=>{
    console.error('err', err.msg)
  })
}

const emit = defineEmits(['listChange'])

const token = getToken();

const headers = { Authorization: `${token}` }

const handleUploadSuccess = (data: any, uploadFile: any, type: string, photoType: string) => {
  if (data.success == true) {
    console.log('data', data)
    formItem.scenePic = data.data[0]
    formItem.uploadPhotoDtoList = [{
      url: data.data[0],
      name: '场景图片'
    }]
    console.log('formItem.scenePic', formItem.scenePic)
    ElMessage.success(data.msg)
  } else {
    ElMessage.error(data.msg);
  }
}

const removeItem = (i: any) => {
  // console.log('remove-item', i)
  const removeIndex = formItem.uploadPhotoDtoList.findIndex((item: any) => i.uploadUrl == item.uploadUrl)
  formItem.uploadPhotoDtoList.splice(removeIndex, 1)
  // console.log('formItem.uploadPhotoDtoList', formItem.uploadPhotoDtoList)
}

const handleUploadError = (err: any) => {
  const message = JSON.parse(err.toString().replace('UploadAjaxError: ', '')).msg
  ElMessage.error(message)
}

const dialogImageUrl = ref('')
const dialogVisible2 = ref(false)

const handlePictureCardPreview = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible2.value = true
}

const createData = async () => {
  const valid = await validate(articleFormRef)
  if (valid) {
    addScene(formItem)
    .then(() => {
      // TODO use res data
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('创建成功！')
    })
    .catch(() => {
      dialogVisible.value = false
      ElMessage.error('创建失败！')
    })
  }
}

const updateData = async () => {
  const valid = await validate(articleFormRef)
  if (valid) {
    if (formItem.equipList.length) {
      formItem.equipIdList = [...new Set([...formItem.equipIdList, ...formItem.equipList.map((i:any) => i.id)])] as any
    }
    editScene(formItem)
    .then(() => {
      // TODO use res data
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('更新成功！')
    })
    .catch(() => {
      dialogVisible.value = false
      ElMessage.error('更新失败！')
    })
  }
}

defineExpose({ dialogVisible, isDisabled, formItem, dialogStatus, getEquipment, reset })



// 设备列表
const availEquipList = ref<equipOrgItem[]>([]);
const equipCasProps = {
  value: "id",
  label: "name",
  multiple: true,
};
const getOrgAvailEquipList = async (v: string | null) => {
  if (!v) return (availEquipList.value = []);
  const res = await apiGetOrgEquipList(v);
  availEquipList.value = res.data;
};
// orgid ==> 当前 org 对应 设备列表
watch(() => formItem.orgId, getOrgAvailEquipList);

// 设备列表变更，触发 equipIdList 字段变更
const onEquipChange = (e: [number, number][]) => {
  formItem.equipIdList = e.map((i) => i.at(-1)) as any
};

// 设备上已经存在的设备删除
const onExistEquipDel = async (id: number) => {
  const list = (formItem.equipList as equipItem[]).filter(i => i.id !== id);
  formItem.equipIdList= list.map(i => i.id) as any
  // 已经存在的设备删除，要求下面的选择框重新获取，否则已经存在的设备删除，下面的选择框拉不到
  await editScene(formItem)
  await getOrgAvailEquipList(formItem.orgId)
  formItem.equipList = list as any
  ElMessage.success('删除成功！')
};

</script>
<style lang="scss" scoped>
.el-upload__tip {
  line-height: 20px;
}
.add-no {
  :deep(.el-upload-list) {
    .el-upload-list__item + .el-upload {
      display: none;
    }
  }
}
.scene-dialog {
  margin-top: 10px;
  p {
    margin-top: 0;
  }
  &:after {
    content: '';
    display: table;
    clear: both;
  }
}

.exist {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}
</style>
